package com.wly.packet;

import java.lang.reflect.Method;
import java.util.HashMap;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.wly.define.PacketDefine;

public class PacketFactory
{

	private static PacketFactory _instance = null;
	private static HashMap<Integer, String> classInfo;

	static private Logger log = LoggerFactory.getLogger("PacketFactory");
	
	private PacketFactory()
	{
		initClassInfo();
	}
	
	static public PacketFactory getInstance()
	{
		if(_instance == null)
		{
			_instance = new PacketFactory();
		}
		return _instance;
	}
	
	private void initClassInfo()
	{
		classInfo = new  HashMap<Integer, String>();
		classInfo.put(PacketDefine.CS_LOGIN, "com.wly.packet.CSLoginPacket");
		classInfo.put(PacketDefine.SC_INT_MESSAGE, "com.wly.packet.SCIntMessage");
		classInfo.put(PacketDefine.CS_INT_MESSAGE, "com.wly.packet.CSIntMessage");
		classInfo.put(PacketDefine.SC_STRING_MESSAGE, "com.wly.packet.SCStringMessage");
		classInfo.put(PacketDefine.CS_STRING_MESSAGE, "com.wly.packet.CSStringMessage");
		classInfo.put(PacketDefine.SC_FULL_PALYER, "com.wly.packet.SCPlayer");
		classInfo.put(PacketDefine.SC_FIGHT_RESULT, "com.wly.packet.SCFightResult");
	}
	
	public Packet decodeObject(int type, byte[] byteArr)
	{
		try
		{
			Packet pkg;
			String className = (String)classInfo.get(type);
			if(className == null)
			{
				log.info("unKown packet type:" + type);
				return null;
			}
			Class cls = Class.forName(className);
			pkg = (Packet)cls.newInstance();
			pkg.unSerialization(byteArr);
			return pkg;
		}
		catch (Exception e)
		{
			System.out.println("Exception:");
			e.printStackTrace();
			return null;
		}
	}
}
